#include "UITextEntry.h"
#include <sstream>

namespace Lame3d
{
	UITextEntry::UITextEntry(const std::string &n, const Point2d &l, const Point2d &s)
			: UIElement(n, l, s), text(""), hasFocus(false), isProtected(false), cursorIdx(0)
	{
	}
	
	UITextEntry::~UITextEntry()
	{
	}
	
	const std::string& UITextEntry::Text() const
	{
		return text;
	}
	
	void UITextEntry::Text(const std::string &t)
	{
		text = t;
	}
	
	const std::string& UITextEntry::TextWithCursor()
	{
		if(hasFocus) {
			std::stringstream sstr;
			sstr << text.substr(0, cursorIdx);
			sstr << "|";
			if(cursorIdx < text.size()) {
				sstr << text.substr(cursorIdx);
			}
			textWithCursor = sstr.str();
			return textWithCursor;
		} else {
			return text;
		}
	}
	
	void UITextEntry::Clear()
	{
		text.clear();
		cursorIdx = 0;
	}
	
	void UITextEntry::Insert(char c)
	{
		printf("Inserting %c\n", c);
		text.insert(cursorIdx++, &c);
	}
	
	void UITextEntry::Backspace()
	{
		if(cursorIdx > 0) {
			text.erase(--cursorIdx, 1);
		}
	}
	
	void UITextEntry::Delete()
	{
		if(cursorIdx < text.size() - 1) {
			text.erase(cursorIdx, 1);
		}
	}
	
	void UITextEntry::Left()
	{
		if(cursorIdx > 0) {
			--cursorIdx;
		}
	}
	
	void UITextEntry::Right()
	{
		if(cursorIdx < text.size()) {
			++cursorIdx;
		}
	}
	
	void UITextEntry::Home()
	{
		cursorIdx = 0;
	}
	
	void UITextEntry::End()
	{
		
		cursorIdx = text.size();
		if(text.size() == 0) {
			cursorIdx = 0;
		}
	}
	
	bool UITextEntry::HasFocus() const
	{
		return hasFocus;
	}
	
	void UITextEntry::HasFocus(bool b)
	{
		hasFocus = b;
	}
	
	void UITextEntry::Handle(const KeyEvent &e)
	{
		if(e.Key() == SDLK_ESCAPE) {
			hasFocus = false;
		} else if(e.Key() == SDLK_RETURN) {
			// do something related to a full entry.
		} else if(e.Key() == SDLK_LEFT) {
			Left();
		} else if(e.Key() == SDLK_RIGHT) {
			Right();
		} else if(e.Key() == SDLK_END) {
			End();
		} else if(e.Key() == SDLK_HOME) {
			Home();
		} else if(e.Key() == SDLK_BACKSPACE) {
			Backspace();
		} else if(e.Key() == SDLK_DELETE) {
			Delete();
		} else if(e.IsText()) {
			Insert(e.Character());
		}
	}
	
	const std::string& UITextEntry::EnterMessage() const
	{
		return enterMessage;
	}
	
	void UITextEntry::EnterMessage(const std::string &s)
	{
		enterMessage = s;
	}
	
	int UITextEntry::CursorIndex() const 
	{
		return cursorIdx;
	}
}
